<?php 
namespace app\wework\model\user\lost;
use think\facade\Db;
use think\facade\Session;

/**
* 流失提醒
**/
class LostCustomerModel {
	static public $wid;
	/**
	 * 获取流失提醒信息
	 * @param $page 分页
	 * @param $type 类型
	 * @param $staffs 员工筛选
	 * @param $add_time 添加时间
	 * @param $lossing_time 流失时间
	 * @param $days 添加天数
	 * @param $tags 标签
	 * @return 
	 */
 	static public function list($page,$size,$type,$staffs=NULL,$add_time=NULL,$lossing_time=NULL,$days=NULL,$tags=NULL,$wid=NULL){
 		$wid = Session::get('wid')?:$wid;
		$res = Db::table('kt_wework_customer_lossing')
					->alias('l')
					->join(['kt_wework_customer'=>'c'],'l.external_userid = c.external_userid and l.staff_id = c.staff_id')
					->join(['kt_wework_staff'=>'w'],'l.staff_id = w.id');
			if($tags){
				foreach ($tags as $value){
					$where = [];
		            $where[0] = ["l.wid","=",$wid];
		            $where[0] = ["l.type","=",$type];
		            if($staffs)$where[0] = ["l.staff_id","in",$staffs];
		            $where[0] = ["c.tags","like","%\"{$value}\"%"];
					$res = $res->whereOr($where);
				}
			}else{
				$where["l.wid"] = $wid;
		 		$where["l.type"] = $type;
		 		if($staffs) $where["l.staff_id"] = $staffs;
				$res = $res->where($where);
			}
			if($add_time) $res = $res->whereBetweenTime('l.add_time', $add_time[0], $add_time[1]);
			if($lossing_time) $res = $res->whereBetweenTime('l.lossing_time', $lossing_time[0], $lossing_time[1]);
			if($days) $res = $res->whereBetweenTime('l.days', $days[0], $days[1]);
			$data['count'] = $res->count();
			$data['item'] = $res->field("c.id,c.name,c.avatar,c.tags,w.name as staff_name,l.lossing_time,l.add_time,l.days")
							->page($page,$size)
							->json(["tags"])
							->filter(function($data){
								$tag_info = Db::table("kt_wework_tag")->where(["tag_id"=>$data["tags"]])->field("tag_name")->select()->toArray();
									$data["tag_info"] = array_column($tag_info, "tag_name");
									return $data;
								})->select()
							->toArray();
			$data['page'] = $page;
			$data['size'] = $size;
			$data['wid'] = $wid;
		return $data;
	}

	static public function getSet(){
		$wid = Session::get("wid");
		$res = Db::table('kt_wework_customer_lossing_status')->where(["wid"=>$wid])->find();

		return $res?$res["status"]:0;
	}

	//删人提醒开关
	static public function updates($status){
		$wid = Session::get("wid");
		$set = Db::table('kt_wework_customer_lossing_status')->where(["wid"=>$wid])->find();
		if($set)$res = Db::table('kt_wework_customer_lossing_status')->where(["wid"=>$wid])->update(["status"=>$status]);
		if(!$set){
			$data["wid"] = $wid;
			$data["status"] = $status;
			$res = Db::table('kt_wework_customer_lossing_status')->insertGetId($data);
		}
		return $res;
	}
}